<?php
/**
 * Created by PhpStorm.
 * User: Victor
 * Date: 2019/5/6
 * Time: 14:02
 */

namespace app\worker\controller;

use app\flash\model\CurrencyHangqing;
use QL\QueryList;
use Workerman\Worker;
use Workerman\Lib\Timer;
use think\Db;
use think\Exception;

class TimerList
{
    public function __construct()
    {
        echo '进来了';

        //$this->test();
        /*Timer::add(1, array($this, 'test'));*/
        //$this->coin();
        //$this->hangqing();
        //$this->kuaixun();
        //$this->shendu();
//        Timer::add(1, array($this, 'coin'));

        $this->bourse();
        Timer::add(300, array($this, 'hangqing'));
        Timer::add(60, array($this, 'coin_rate'));
        Timer::add(600, array($this, 'kuaixun'));
        Timer::add(600, array($this, 'shendu'));
        Timer::add(3600, array($this, 'bourse'));
    }

    //汇率
    public function coin_rate()
    {
        $data = file_get_contents('http://www.feixiaohao.com/');
        preg_match('|unitList:{(.*?)}|', $data, $info);
        $info = $info[1];
        preg_match_all('|(\w+):\["(.*?)",(.*?),"(.*?)"\]|', $info, $info1);
        $arr = [];
        for ($i = 0; $i < count($info1[1]); $i++) {
            $str = substr($info1[3][$i], 0, 1);
            if ($str == '.') {
                $info1[3][$i] = '0' . $info1[3][$i];
            }
            $data = [
                'name' => $info1[1][$i],
                'sign' => $info1[2][$i],
                'rate' => $info1[3][$i],
                'mingcheng' => $info1[4][$i],
            ];
            //判断货币表是否存在，不在则插入,存在则更新
            $iscurrency = Db::name('currency_rate')->where('name', $data['name'])->find();
            if (empty($iscurrency)) {
                //插入
                Db::name('currency_rate')->insertGetId($data);
            } else {
                //更新
                Db::name('currency_rate')->where('name', $data['name'])->update($data);
            }
        }
    }

    //行情
    public function hangqing()
    {
        $opt = array(
            'http' => array(
                'header' => array(
                    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36" .
                    "Accept: application/json, text/plain, */*" .
                    "Referer: https://www.feixiaohao.com/" .
                    "Sec-Fetch-Mode: cors",
                ),
            ),
        );
        $context = stream_context_create($opt);
        $i = 1;
        $timeId = Timer::add(3, function () use (&$i, &$timeId, $context) {
            if ($i > 35)
                Timer::del($timeId);
            $url = 'http://dncapi.bqiapp.com/api/coin/web-coinrank?page=' . $i . '&type=-1&pagesize=100&webp=1';
            $data = @file_get_contents($url, false, $context);
            $responses = json_decode($data, true);
            if (!isset($responses['data'])) return;
            foreach ($responses['data'] as $response) {
                $model = new CurrencyHangqing();
                try {
                    if (count($response) > 0) {
                        $code = $response['code'];
                        $iscurrency = Db::name('currency_hangqing')->where('code', $code)->find();
                        if ($iscurrency) {
                            $model->allowField(true)->save($response, ['code' => $code]);
                        } else {
                            $model->allowField(true)->save($response);
                        }
                    }
                } catch (\Exception $e) {
                    echo $e->getMessage();
                }
            }
            $i++;
        });
        echo '数字货币行情采集成功';
    }

    //数字货币信息
    public function coin()
    {
        $url = 'http://dncapi.bqiapp.com/api/coin/data_list?webp=1';
        $data = file_get_contents($url);
        $response = json_decode($data, true);
        //dump($response);die;
        if ($response['code'] == 200) {
            $arr = $response['data'];
            $count = count($arr);
            for ($i = 0; $i < $count; $i++) {
                if ($arr[$i]['type'] == 1) {
                    //判断货币表是否存在，不在则插入,存在则更新
                    $iscurrency = Db::name('currency')->where(array('code' => $arr[$i]['code']))->find();
                    if (empty($iscurrency)) {
                        //插入
                        Db::name('currency')->insertGetId($arr[$i]);
                    } else {
                        //更新
                        Db::name('currency')->where(array('code' => $arr[$i]['code']))->update($arr[$i]);
                    }
                }

            }
        }
        echo '数字货币采集成功';
    }

    //快讯
    public function kuaixun()
    {
        $url = 'https://www.bishijie.com/kuaixun.html';
        $rulers = [
            //文章标题
            'article_id' => ['.kuaixun_list ul', 'data-id'],
            //文章标题
            'title' => ['.kuaixun_list h2 a', 'text'],
            // //发布日期
            'date' => ['.kuaixun_list ul>span', 'text'],
            //文字内容
            'content' => ['.kuaixun_list  div>a ', 'text'],
            'url' => ['.kuaixun_list ul>li>li>a', 'href']
        ];
        $data = QueryList::Query($url, $rulers)->data;
        // $arr = [];
        foreach ($data as $key => $value) {
            $search = array(" ", "　", "\n", "\r", "\t");
            $replace = array("", "", "", "", "");
            $content = str_replace($search, $replace, $value['content']);
            $arr[] = array(
                'article_id' => $value['article_id'],
                'title' => $value['title'],
                'time' => $value['date'],
                'datetime' => strtotime(date("Y-m-d H:i:s")),
                'details' => json_encode($content)
            );

        }
        $count = count($arr);
        for ($i = 0; $i < $count; $i++) {
            //$mysql = Db::name('flashs')->insert($arr[$i],true);
            //判断否存在，不在则插入,存在则更新
            $iscurrency = Db::name('flashs')->where(array('article_id' => $arr[$i]['article_id']))->find();
            if (empty($iscurrency)) {
                //插入
                Db::name('flashs')->insertGetId($arr[$i]);
            } else {
                //更新
                Db::name('flashs')->where(array('article_id' => $arr[$i]['article_id']))->update($arr[$i]);
            }
        }
        echo '快讯采集成功';
    }

    //深度
    public function shendu()
    {
        $url = "https://www.bishijie.com/shendu.html";
        $rulers = [
            //文章标题
            'title' => ['.cTitle a', 'text'],
            'picture' => ['.cImg', 'src'],
            'source' => ['.laiyuan', 'text'],
            'content' => ['.cRight p', 'text'],
            'id' => ['.container>a', 'href'],
        ];
        $data = QueryList::Query($url, $rulers)->data;
        foreach ($data as $key => $v) {
            $data[$key]['content_id'] = substr($v['id'], 8);
            $data[$key]['title'] = \replace($v['title']);
            // $data[$key]['title'] = str_replace('置顶原创','',$data[$key]['title']);
            $arr = $this->details($v['id']);
            unset($data[$key]['id']);
            $data[$key]['details'] = \json_encode($arr[0]['contentContainer']);
            $data[$key]['time'] = strtotime(date('Y-m-d H:i:s'));
        }
        $count = count($data);
        for ($i = 0; $i < $count; $i++) {
            $iscurrency = Db::name('deepness')->where(array('content_id' => $data[$i]['content_id']))->find();
            if (empty($iscurrency)) {
                //插入
                Db::name('deepness')->insertGetId($data[$i]);
            } else {
                //更新
                Db::name('deepness')->where(array('content_id' => $data[$i]['content_id']))->update($data[$i]);
            }
        }
        echo '深度采集成功';
    }

    public function details($id)
    {
        $url = "https://m.bishijie.com" . $id;
        $rulers = [
            'contentContainer' => ['.content', 'html'],
        ];
        $data = QueryList::Query($url, $rulers)->data;
        foreach ($data as $key => $value) {
            $str= preg_replace('/src="[^<>]+" data-src/', 'src', $data['0']['contentContainer']);
            $data[$key]['contentContainer'] = $str;
        }
        return $data;
    }

    //交易所的采集
    public function bourse()
    {
        $url = 'https://www.bishijie.com/exchanges';
        $rulers = [
            'bourse_logo' => ['.cur_logo>img', 'src'],
            'bourse_name' => ['.cur_info_box>h2>a', 'text'],
            'bourse_business' => ['td:eq(1)>span', 'text'],
            'bourse_type' => ['td:eq(2)>.cur_info_s', 'html'],
            'bourse_text' => ['.jytit', 'text'],
            'bourse_support' => ['td:eq(3)>.jyinfo', 'html']
        ];
        $range = '#exchange_table>#table_body>tr';
        $data = QueryList::Query($url, $rulers, $range)->data;
        //var_dump($data);die;
        foreach ($data as $key => $value) {
            $type = $value['bourse_type'];
            $type = str_replace("<i>", "", $type);
            $type = str_replace("</i>", ",", $type);
            $type = trim($type, ',');
            $value['bourse_type'] = $type;
            $res = Db::table('bourse')->where(['bourse_name' => $value['bourse_name']])->find();
            if (empty($res)) {
                try {
                    $insert = Db::table('bourse')->insert($value);
                } catch (\Exception  $e) {
                    return json($e->getMessage());
                }


            } else {
                try {
                    $insert = Db::table('bourse')->where(['bourse_name' => $value['bourse_name']])->update($value);
                } catch (\Exception $e) {
                    return json($e->getmessage());
                }

            }
        }
        echo '交易所采集成功';
    }
}